package com.cskaoyan.realm;

import com.cskaoyan.mapper.UserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

//管理员登录
@Component
public class AdminRealm extends AuthenticatingRealm {

    @Autowired
    UserMapper userMapper;

    // @param authenticationToken → subject执行login时传入的UsernamePasswordToken

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //principal就是usernamePasswordToken中的用户名
        String principal = (String) authenticationToken.getPrincipal();
        //查询到数据库中这个用户名对应的密码
        String password = selectFromDB(principal);//mapper调用数据库方法
        //第一个参数：放入到系统中的用户信息,塞入的是什么类型的用户信息，后续取出就是什么类型的
        //第二个参数：系统中维护的正确的密码
        return new SimpleAuthenticationInfo(principal,password,this.getName());
        //认证器在认证过程中：比对token中的password和authenticationInfo中的password
    }
    /*@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权在认证的基础上做的 → 已经认证的状态意味着系统中已经包含了认证信息
        //获得系统中的用户信息 → new SimpleAuthenticationInfo(principal
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        //可以查询权限列表 → mapper
        List<String> permissions = permissionFromDb(primaryPrincipal);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);


        return simpleAuthorizationInfo;
    }*/

    private String selectFromDB(String principal) {
        return "admin123";
    }
    /*private List<String> permissionFromDb(String primaryPrincipal) {
        return Arrays.asList("eat","sleep","study");
    }*/

}
